package com.artisan.provider.controller;



import com.artisan.provider.ImportConfig.UserImportConfig;
import com.artisan.provider.domain.TPromotionSeckill;
import com.artisan.provider.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 第二个版本提交
 */
@RestController
public class ProductController implements UserImportConfig {

    Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductService productService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("port")
    private String port;

    @Override
    public List<Object> findAll(Object zgIntegralDto, int page, int limit) {
        return null;
    }

    @Override
    public ModelAndView showGoods() {
        logger.info("gid:");
        ModelAndView mav = new ModelAndView("/goods");
        System.out.println("请求进来了......");
        return mav;
    }

    //redis解决超发问题
    @Override
    public void showGoodsSeckill() {

        List<TPromotionSeckill> list = productService.findUnstartSecKill();
        for (TPromotionSeckill tPromotionSeckill : list) {
            System.out.println(tPromotionSeckill.getPsId() + "秒杀活动已经启动");
            tPromotionSeckill.setStatus(1);
            productService.update(tPromotionSeckill);
        }

    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void showGoodsSeckillTExt() {

        List<TPromotionSeckill> list = productService.findUnstartSecKill();
        for (TPromotionSeckill tPromotionSeckill : list) {
            System.out.println(tPromotionSeckill.getPsId() + "秒杀活动已经启动");
            //删除重复的业务
            redisTemplate.delete("seckill:count:"+tPromotionSeckill.getPsId());
            //有多少个库存遍历商品id
            for (Integer i = 0; i < tPromotionSeckill.getPsCount(); i++) {
                redisTemplate.opsForList().rightPush("seckill:count:"+tPromotionSeckill.getPsId(),tPromotionSeckill.getGoodsId());
            }
            tPromotionSeckill.setStatus(1);
            productService.update(tPromotionSeckill);
        }

    }

    /**
     * 秒杀活动方法 秒杀入口.......................................抢购入口
     */
    public Map processSecKill(int psId,String userId){
        Map result = new HashMap();
        try {
            productService.promotionSecKillService(psId,userId,1);
            //从mq中获取订单编号
            String orderNo = productService.sendOrderToQueue(userId);
            Map data = new HashMap();
            data.put("orderNo",orderNo);
            result.put("code","0"); //0代表操作成功
            result.put("message","success");
            result.put("data",data);
        } catch (Exception e) {
            result.put("code","500");
            result.put("message",e.getMessage());
        }

        return result;
    }

    @Override
    public String login(String u, WebRequest request) {
        request.setAttribute("user",u,WebRequest.SCOPE_SESSION);
        return "port:"+port+"login success";
    }

    @Override
    public String checkUser(WebRequest request) {
        //从session 获取登录信息  在启动类配置@EnableRedisHttpSession 集群下就可使用
        String user = (String) request.getAttribute("user",WebRequest.SCOPE_SESSION);
        if(user != null){
            return "port"+port+",user="+user;
        }else {
            return "port"+port+",redirect to login!";
        }

    }

    /**
     * 设置过期活动
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void endSecKill(){

            List<TPromotionSeckill> list = productService.findExpriceSecKill();
        for (TPromotionSeckill ps : list) {
            System.out.println(ps.getPsId()+"秒杀活动已结束");
            ps.setStatus(2);
            productService.update(ps);

            //活动结束,原有库存清零
            redisTemplate.delete("seckill:count:"+ps.getPsId());
        }
    }






}
